package httpCtrler

import (
	"fmt"
	jwt "github.com/appleboy/gin-jwt"
	"github.com/gin-gonic/gin"
	"github.com/go-xorm/xorm"
	"io"
	st "kjjcgroup_server/model"
	sv "kjjcgroup_server/service"
	"net/http"
	"os"
	"path/filepath"
	"strconv"
	"time"
)

func UploadRouter(router *gin.Engine, routerAuth *gin.RouterGroup) {
	router.GET("/upFileType", upFileTypeQuery)
	LogMap["/upFileType"] = "查询文件类型"
	routerAuth.PUT("/upFileTypeAdd", upFileTypeAddQuery)
	LogMap["/upFileTypeAdd"] = "添加文件类型"
	routerAuth.PUT("/upFileTypeEdit", upFileTypeEditQuery)
	LogMap["/upFileTypeEdit"] = "编辑文件类型"
	routerAuth.DELETE("/upFileTypeDel", upFileTypeDelQuery)
	LogMap["/upFileTypeDel"] = "删除文件类型"
	/*===============上传文件================*/
	routerAuth.POST("/upFile", upFile)
	LogMap["/upFile"] = "上传文件"
	router.GET("/upFileSea", uploaded)
	LogMap["/upFileSea"] = "查询上传的文件"
	routerAuth.POST("/upFileEdit", upFileEditQuery)
	LogMap["/upFileEdit"] = "更新上传的文件分类"
	routerAuth.POST("/delUpFile", dUpload)
	LogMap["/delUpFile"] = "删除上传的文件，传入DelFls:[UID,UID]"
}

func upFile(c *gin.Context) {
	//c.Request.FormFile()
	err := c.Request.ParseMultipartForm(1024 * 1024 * 10)
	if err != nil {
		return
	}
	fmt.Println("-----")
	for v := range c.Request.MultipartForm.File {
		fmt.Println(v)
	}
	thrCode := c.Query("UperCode")
	clm := jwt.ExtractClaims(c)
	if thrCode == "" {
		thrCode = clm[SessUserAccount].(string)
	}
	file, header, err := c.Request.FormFile("file")
	filename := header.Filename
	fmt.Println(header.Filename)

	fGuid := sv.GetUID()
	//upName := fmt.Sprintf("%d_%d", time.Now().Unix()-_StartDate, atomic.AddInt64(&_ContinueNum, 1))
	out, err := os.Create("./upload/" + fGuid + filepath.Ext(filename))
	if err != nil {
		c.JSON(http.StatusBadRequest, &MsgReturn{Msg: "failed", Data: err.Error()})
		return
	}
	defer out.Close()
	_, err = io.Copy(out, file)

	var eng *xorm.Engine
	if err == nil {
		eng, err = sv.GetEngine()
	}
	var sess *xorm.Session
	if err == nil {
		defer eng.Close()
		sess = eng.NewSession()
		defer sess.Close()
		sess.Begin()
		t := time.Now()
		t = time.Date(t.Year(), t.Month(), t.Day(), t.Hour(), t.Minute(), t.Second(), 0, time.Local)
		_, err = sess.Insert(&st.UpFile{Uid: fGuid, Fname: filepath.Base(filename), Ftype: filepath.Ext(filename), UperCode: thrCode, UpdateTime: t})
	}

	print(filepath.Base(filename))
	if err != nil {
		sess.Rollback()
		c.JSON(http.StatusBadRequest, &MsgReturn{Msg: "failed", Data: err.Error()})
	} else {
		if err = sess.Commit(); err != nil {
			c.JSON(http.StatusBadRequest, &MsgReturn{Msg: "failed", Data: err.Error()})
		} else {
			rtnDt := &struct {
				FCode string `json:"filePath" `
				Fdown string `json:"fdown" `
			}{}
			rtnDt.FCode = filename
			rtnDt.Fdown = fGuid + filepath.Ext(filename)
			c.JSON(http.StatusOK, rtnDt)
		}
	}
}

func dUpload(c *gin.Context) {
	resDt := &struct {
		DelItems []string `json:"DelFls" `
	}{}
	if err2 := c.BindJSON(resDt); err2 != nil {
		c.JSON(http.StatusBadRequest, &MsgReturn{Msg: "failed", Data: err2.Error()})
		return
	}

	eng, err := sv.GetEngine()
	var sess *xorm.Session
	if err == nil {
		defer eng.Close()
		eng.ShowSQL(isShowSQL())
		sess = eng.NewSession()
	}
	var FileCode string
	for i := 0; i < len(resDt.DelItems); i++ {
		FileCode = resDt.DelItems[i]
		if err == nil {
			_, err = sess.ID(FileCode).Delete(&st.UpFile{})
		}
	}

	if err == nil {
		if err = sess.Commit(); err != nil {
			c.JSON(http.StatusBadRequest, &MsgReturn{Msg: "failed", Data: err.Error()})
		} else {
			c.JSON(http.StatusOK, &MsgReturn{Msg: "OK", Data: "ok"})
		}
		return
	} else {
		sess.Rollback()
	}

	c.JSON(http.StatusBadRequest, &MsgReturn{Msg: "failed", Data: err.Error()})
}

func uploaded(c *gin.Context) {
	uid := c.Query("uid")
	ftype := c.Query("ftype")
	uperCode := c.Query("uperCode")
	typeId := c.Query("typeId")
	pageIdx, pageCnt := Page(c)
	if pageIdx == -1 {
		pageIdx = 0
	}
	if pageCnt == -1 {
		pageCnt = 10
	}
	mysql, err := sv.GetEngine()
	if err != nil {
		c.JSON(409, &MsgReturn{Msg: "Open DataBase Failed", Data: nil})
		return
	}
	defer func(mysql *xorm.Engine) {
		err := mysql.Close()
		if err != nil {
			return
		}
	}(mysql)
	mysql.ShowSQL(isShowSQL())

	var collArr []*st.UpFile
	var collArr1 []*st.UpFile
	var count int64
	if typeId != "" {
		err = mysql.Where("type_id=?", typeId).Limit(pageCnt, pageIdx*pageCnt).Find(&collArr)
		count, _ = mysql.Where("type_id=?", typeId).FindAndCount(&collArr1)
	} else if uid != "" {
		err = mysql.Where("uid=?", uid).Find(&collArr)
	} else if ftype != "" {
		err = mysql.Where("ftype=?", ftype).Limit(pageCnt, pageIdx*pageCnt).OrderBy("update_time desc").Find(&collArr)
		count, _ = mysql.Where("ftype=?", ftype).FindAndCount(&collArr1)
	} else if uperCode != "" {
		err = mysql.Where("uper_code=?", uperCode).Limit(pageCnt, pageIdx*pageCnt).OrderBy("update_time desc").Find(&collArr)
		count, _ = mysql.Where("uper_code=?", uperCode).FindAndCount(&collArr1)
	} else {
		err = mysql.Limit(pageCnt, pageIdx*pageCnt).OrderBy("update_time desc").Find(&collArr)
		count, _ = mysql.FindAndCount(&collArr1)
	}
	if err != nil {
		fmt.Println(err)
		c.JSON(409, &MsgReturn{Msg: "failed", Data: nil})
		return
	}
	rtnDt := rtnData(count, pageCnt, pageIdx, collArr)
	c.JSON(http.StatusOK, &MsgReturn{Msg: http.StatusText(http.StatusOK), Data: rtnDt})
}

func upFileEditQuery(c *gin.Context) {
	resDt := &st.UpFile{}
	err := c.BindJSON(resDt)
	if err != nil {
		return
	}
	fmt.Printf("JhVar %+v \r\n", resDt)

	mysql, err := sv.GetEngine()
	mysql.ShowSQL(isShowSQL())
	if err != nil {
		c.JSON(409, "")
		return
	}
	defer func(mysql *xorm.Engine) {
		err := mysql.Close()
		if err != nil {

		}
	}(mysql)
	sess := mysql.NewSession()
	defer sess.Close()
	err = sess.Begin()
	if err != nil {
		return
	}
	_, err = sess.Where("uid=?", resDt.Uid).Update(&st.UpFile{TypeId: resDt.TypeId})
	if err != nil {
		err := sess.Rollback()
		if err != nil {
			return
		}
	} else {
		err = sess.Commit()
	}
	if err != nil {
		c.JSON(409, err.Error())
		return
	}
	c.JSON(http.StatusOK, &MsgReturn{Msg: "OK", Data: "id:" + strconv.Itoa(resDt.TypeId) + " 编辑成功!"})
}

func upFileTypeQuery(c *gin.Context) {
	typeId := c.Query("typeId")
	typeFile := c.Query("typeFile")
	parentId := c.Query("parentId")
	mysql, err := sv.GetEngine()
	if err != nil {
		c.JSON(409, &MsgReturn{Msg: "Open DataBase Failed", Data: nil})
		return
	}
	defer func(mysql *xorm.Engine) {
		err := mysql.Close()
		if err != nil {
			return
		}
	}(mysql)
	mysql.ShowSQL(isShowSQL())

	var collArr []*st.UpFileTypeMod
	if typeId != "" {
		err = mysql.Where("type_id=? and type_file=?", typeId, typeFile).OrderBy("type_id asc").Find(&collArr)
	} else if parentId != "" {
		err = mysql.Where("parent_id=? and type_file=?", parentId, typeFile).OrderBy("type_id asc").Find(&collArr)
	} else {
		err = mysql.Where("type_file=?", typeFile).OrderBy("type_id asc").Find(&collArr)
	}
	if err != nil {
		fmt.Println(err)
		c.JSON(409, &MsgReturn{Msg: "failed", Data: nil})
		return
	}
	c.JSON(http.StatusOK, &MsgReturn{Msg: http.StatusText(http.StatusOK), Data: collArr})
}

func upFileTypeAddQuery(c *gin.Context) {
	resDt := &st.UpFileTypeMod{}
	err := c.BindJSON(resDt)
	if err != nil {
		return
	}
	fmt.Printf("JhVar %+v \r\n", resDt)

	mysql, err := sv.GetEngine()
	mysql.ShowSQL(isShowSQL())
	if err != nil {
		c.JSON(409, "")
		return
	}
	defer func(mysql *xorm.Engine) {
		err := mysql.Close()
		if err != nil {

		}
	}(mysql)
	sess := mysql.NewSession()
	defer sess.Close()

	err = sess.Begin()
	if err != nil {
		return
	}
	t := time.Now()
	t = time.Date(t.Year(), t.Month(), t.Day(), t.Hour(), t.Minute(), t.Second(), 0, time.Local)
	_, err = sess.Cols("type_name", "parent_id", "type_file", "create_time", "update_time").InsertOne(&st.UpFileTypeMod{TypeName: resDt.TypeName, ParentId: resDt.ParentId, TypeFile: resDt.TypeFile, CreateTime: t, UpdateTime: t})
	if err != nil {
		err := sess.Rollback()
		if err != nil {
			return
		}
	} else {
		err = sess.Commit()
	}
	if err != nil {
		c.JSON(409, err.Error())
		return
	}
	c.JSON(http.StatusOK, &MsgReturn{Msg: http.StatusText(http.StatusOK), Data: "添加" + resDt.TypeName + "成功!"})
}

func upFileTypeEditQuery(c *gin.Context) {
	resDt := &st.UpFileTypeMod{}
	err := c.BindJSON(resDt)
	if err != nil {
		return
	}
	fmt.Printf("JhVar %+v \r\n", resDt)

	mysql, err := sv.GetEngine()
	mysql.ShowSQL(isShowSQL())
	if err != nil {
		c.JSON(409, "")
		return
	}
	defer func(mysql *xorm.Engine) {
		err := mysql.Close()
		if err != nil {

		}
	}(mysql)
	sess := mysql.NewSession()
	defer sess.Close()
	err = sess.Begin()
	if err != nil {
		return
	}
	_, err = sess.Where("type_id=?", resDt.TypeId).Update(&st.UpFileTypeMod{TypeName: resDt.TypeName, ParentId: resDt.ParentId})
	if err != nil {
		err := sess.Rollback()
		if err != nil {
			return
		}
	} else {
		err = sess.Commit()
	}
	if err != nil {
		c.JSON(409, err.Error())
		return
	}
	c.JSON(http.StatusOK, &MsgReturn{Msg: http.StatusText(http.StatusOK), Data: "id:" + strconv.Itoa(resDt.TypeId) + " 编辑成功!"})
}

func upFileTypeDelQuery(c *gin.Context) {
	typeId := c.Query("typeId")
	mysql, err := sv.GetEngBom()
	if err != nil {
		fmt.Println(err)
		c.JSON(409, &MsgReturn{Msg: http.StatusText(http.StatusConflict), Data: nil})
		return
	}
	defer func(mysql *xorm.Engine) {
		err := mysql.Close()
		if err != nil {

		}
	}(mysql)
	_, err = mysql.Where("type_id=?", typeId).Delete(&st.UpFileTypeMod{})
	if err != nil {
		fmt.Println(err)
		c.JSON(409, &MsgReturn{Msg: http.StatusText(http.StatusConflict), Data: nil})
		return
	}
	c.JSON(http.StatusOK, &MsgReturn{Msg: http.StatusText(http.StatusOK), Data: "id:" + typeId + " 删除成功!"})
}
